﻿#define _CRT_SECURE_NO_WARNINGS 1
#pragma warning(disable : 6031)
#include "queue.h"

void queueinit(Queue* pst)
{
	assert(pst);
	pst->head = NULL;
	pst->tail = NULL;
	pst->size = 0;
}

void queuedestroy(Queue* pst)
{
	assert(pst);
	Qnode* cur = pst->head;
	while (cur)
	{
		Qnode* next = cur->next;
		free(cur);
		cur = next;
	}
	pst->head = pst->tail = NULL;
	pst->size = 0;
}

void queuepush(Queue* pst, datatype x)
{
	assert(pst);
	Qnode* newnode = (Qnode*)malloc(sizeof(Qnode));
	if (!newnode)
	{
		perror("malloc");
		return;
	}
	newnode->next = NULL;
	newnode->data = x;

	if (!queueempty(pst))
	{
		pst->tail->next = newnode;
		pst->tail = newnode;
	}
	else
	{
		pst->head = pst->tail = newnode;
	}
	pst->size++;
}

void queuepop(Queue* pst)
{
	assert(pst);
	assert(!queueempty(pst));
	
	if (!pst->head->next)
	{
		free(pst->head);
		pst->head = pst->tail = NULL;
	}
	else
	{
		Qnode* next = pst->head->next;
		free(pst->head);
		pst->head = next;
	}
	pst->size--;
}

bool queueempty(Queue* pst)
{
	assert(pst);
	return pst->head == NULL && pst->tail == NULL;
}

datatype queuefront(Queue* pst)
{
	assert(pst);
	assert(!queueempty(pst));

	return pst->head->data;
}

datatype queueback(Queue* pst)
{
	assert(pst);
	assert(!queueempty(pst));

	return pst->tail->data;
}

datatype queuesize(Queue* pst)
{
	assert(pst);
	return pst->size;
}